from flask import *
import time
from config import Config, gl
from run_xiaoice import run
import threading

app = Flask(__name__)


def rebuild_thread():
    my_th = threading.Thread(target=run)
    my_th.setDaemon(True)
    gl.set_value('th', my_th)


@app.route(Config.path_calling)
def call_xiaoice():
    try:
        th = gl.get_value('th')
        if th.is_alive():
            return render_template('message.html', message='小微已经在运行。')
        th.start()
        return render_template('message.html', message='操作成功。')
    except Exception:
        rebuild_thread()
        th = gl.get_value('th')
        th.start()
        return render_template('message.html', message='操作成功。')


@app.route(Config.path_exiting)
def stop_xiaoice():
    try:
        th = gl.get_value('th')
        if not th.is_alive():
            return render_template('message.html', message='小微没有在运行啊。')
        gl.set_value('running', False)
        while th.is_alive():
            time.sleep(0.1)
        rebuild_thread()
        return render_template('message.html', message='操作成功。')
    except Exception:
        rebuild_thread()
        return render_template('message.html', message='遇到了意外，但是大概操作成功。')


if __name__ == '__main__':
    rebuild_thread()
    app.run(Config.HOST, Config.PORT)
